#ifndef PLY_READER_HH
#define PLY_READER_HH

#include <vector>
#include <fstream>
#include <string>
#include <algorithm>

#include <cgmath/cgmath.hh>
#include "mesh.hh"

// Read a mesh from a file.
void read_ply(const char* file,
              std::vector<cgmath::triangle_3d>& triangles);

class ply_reader {

public:

  int readMesh(std::string plyFile,
               std::vector<float> &vertexData,
               std::vector<unsigned> &indexData);

protected:

  std::string getline(std::ifstream &ifs);

  void splitString(std::string s, std::vector<std::string> &strings);
  int readply(const std::string fileName,
              std::vector<float> &vertexData,
              std::vector<unsigned> &indexData);

  class OrderedTriplet {

  public:

    OrderedTriplet(unsigned x_, unsigned y_, unsigned z_)
    {
      order(x_, y_, z_);

      x = x_;
      y = y_;
      z = z_;
    }

    OrderedTriplet(const OrderedTriplet& trip)
    {
      x = trip.x;
      y = trip.y;
      z = trip.z;
    }

    void order(unsigned& x_, unsigned& y_, unsigned& z_)
    {
      if (y_ < x_) 
        std::swap(x_, y_);
      if (z_ < y_)
        std::swap(y_, z_);
      if (y_ < x_)
        std::swap(x_, y_);
    }

    bool operator<(const OrderedTriplet& trip) const
    {
      if (x < trip.x)
        return true;
      else if (x == trip.x && y < trip.y)
        return true;
      else if (x == trip.x && y == trip.y && z < trip.z)
        return true;
      else
        return false;
    }

    unsigned x;
    unsigned y;
    unsigned z;
  };
  
};

#endif
